package com.beone.admin.controller;

import com.base.SuperController;
import com.base.common.util.BaseStringUtils;
import com.base.common.util.DateUtil;
import com.base.common.util.GeneratorUniqueID;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @title  系统文件上传
 * @Author 覃球球
 * @Version 1.0 on 2018/11/3.
 * @Copyright 贝旺科技
 */
@RestController
@RequestMapping("/system/upload")
public class UploadController extends SuperController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Value("${app.upload.path:/home/upload}")
    private String fileUploadPath;

    /**
     * 上传
     * @param request
     * @return
     */
    @CrossOrigin  //允许跨域访问
    @PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE
        , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object upload(MultipartHttpServletRequest request){
        String fieldName = request.getParameter("fieldName");
        fieldName = StringUtils.isBlank(fieldName) ? "file" : fieldName;
        //上传文件分类 images（图片）、file（文件）、video（视频）、audio（音频）
        String accept = request.getParameter("accept");
        fieldName = StringUtils.isBlank(accept) ? "file" : accept;

        if(logger.isDebugEnabled()){
            logger.debug("上传文件fieldName = {}, accept = {}", fieldName, accept);
        }
        List<MultipartFile> files = request.getFiles(fieldName);
        List<Properties> list = new ArrayList<Properties>();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile multipartFile =  files.get(i);
            //文件扩展名
            String fileExtName = BaseStringUtils.getFileExtName(multipartFile.getOriginalFilename());
            //原文件名
            String originName = multipartFile.getOriginalFilename();

            String subDir = accept + "/" + DateUtil.date2String("yyyyMM");

            File dir = new File(fileUploadPath, subDir);
            if(!dir.exists()){ //检查目录是否存在
                dir.mkdirs();
            }

            //获取文件名
            String fileName = DateUtil.date2String("dd_HHmmss")
                    + "_" + GeneratorUniqueID.createToken() + "." + fileExtName;
            File dest = new File(dir, fileName);
            Properties result = new Properties();

            try {
                multipartFile.transferTo(dest);
                result.put("extName", fileExtName);
                result.put("originName", originName);
                result.put("url",  subDir + "/" + fileName);
                result.put("size",  multipartFile.getSize());
                list.add(result);
            } catch (IOException e) {
                logger.error("file upload 异常 = {}",e.getMessage());
                return super.responseResult("fail", e.getMessage(), null);
            }
        }
        return super.responseResult("success", "", list);
    }
}